package com.tanhua.manage.msg;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.manage.enums.LogTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "tanhua-sso-login",
        consumerGroup = "tanhua-sso-login-consumer")
@Slf4j
public class LoginMsgConsumer implements RocketMQListener<String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 转发消息到tanhua-log中
     *
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);


            Map<String, Object> logMsg = new HashMap<>();
            logMsg.put("userId", jsonNode.get("id").asLong());
            logMsg.put("type", LogTypeEnum.LOGIN.getValue());
            logMsg.put("date", jsonNode.get("date").asText());

            //转发消息
            this.rocketMQTemplate.convertAndSend("tanhua-log", logMsg);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
